﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace MovieMetaDataFinder
{
    public partial class SaveImageFromWeb
    {
        public static byte[] GetBytesFromUrl(string url)
        {
            byte[] b = null;

            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
            using (WebResponse myResp = myReq.GetResponse())
            {

                Stream stream = myResp.GetResponseStream();
                using (BinaryReader br = new BinaryReader(stream))
                {
                    try
                    {
                        b = br.ReadBytes(5000000);
                    }
                    catch { }
                    br.Close();
                }
                myResp.Close();
            }
            return b;
        }


        public static void WriteBytesToFile(string fileName, string url)
        {
            try
            {
                byte[] content = null;

                Program.WebThreadDone = false;

                ThreadPool.QueueUserWorkItem(
                delegate(object state)
                {
                    content = GetBytesFromUrl(url);
                    Program.WebThreadDone = true;
                });
                while (!Program.WebThreadDone)
                {
                    Application.DoEvents();
                }

                using (FileStream fs = new FileStream(fileName, FileMode.Create))
                {
                    using (BinaryWriter w = new BinaryWriter(fs))
                    {
                        try
                        {
                            w.Write(content);
                        }
                        finally
                        {
                            fs.Close();
                            w.Close();
                        }
                    }
                }
            }
            catch { }
        }
    }
}
